2
0

[[...path]].page.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import React from 'react';
  2. import { IUserHasId, IPagePopulatedToShowRevision } from '@growi/core';
  3. import {
  4. GetServerSideProps, GetServerSidePropsContext,
  5. } from 'next';
  6. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  7. import dynamic from 'next/dynamic';
  8. import Head from 'next/head';
  9. import superjson from 'superjson';
  10. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  11. import { MainPane } from '~/components/Layout/MainPane';
  12. import { ShareLinkLayout } from '~/components/Layout/ShareLinkLayout';
  13. import GrowiContextualSubNavigationSubstance from '~/components/Navbar/GrowiContextualSubNavigation';
  14. import RevisionRenderer from '~/components/Page/RevisionRenderer';
  15. import ShareLinkAlert from '~/components/Page/ShareLinkAlert';
  16. import type { PageSideContentsProps } from '~/components/PageSideContents';
  17. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  18. import { SupportedAction, SupportedActionType } from '~/interfaces/activity';
  19. import { CrowiRequest } from '~/interfaces/crowi-request';
  20. import { RendererConfig } from '~/interfaces/services/renderer';
  21. import { IShareLinkHasId } from '~/interfaces/share-link';
  22. import type { PageDocument } from '~/server/models/page';
  23. import { generateSSRViewOptions } from '~/services/renderer/renderer';
  24. import {
  25. useCurrentUser, useCurrentPageId, useRendererConfig, useIsSearchPage, useCurrentPathname,
  26. useShareLinkId, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsSearchScopeChildrenAsDefault, useDrawioUri, useIsContainerFluid,
  27. } from '~/stores/context';
  28. import loggerFactory from '~/utils/logger';
  29. import { NextPageWithLayout } from '../_app.page';
  30. import {
  31. CommonProps, getServerSideCommonProps, generateCustomTitleForPage, getNextI18NextConfig,
  32. } from '../utils/commons';
  33. const logger = loggerFactory('growi:next-page:share');
  34. const PageSideContents = dynamic<PageSideContentsProps>(() => import('~/components/PageSideContents').then(mod => mod.PageSideContents), { ssr: false });
  35. // const Comments = dynamic(() => import('~/components/Comments').then(mod => mod.Comments), { ssr: false });
  36. const ForbiddenPage = dynamic(() => import('~/components/ForbiddenPage'), { ssr: false });
  37. type Props = CommonProps & {
  38. shareLinkRelatedPage?: IShareLinkRelatedPage,
  39. shareLink?: IShareLinkHasId,
  40. isExpired: boolean,
  41. disableLinkSharing: boolean,
  42. isSearchServiceConfigured: boolean,
  43. isSearchServiceReachable: boolean,
  44. isSearchScopeChildrenAsDefault: boolean,
  45. drawioUri: string | null,
  46. rendererConfig: RendererConfig,
  47. };
  48. type IShareLinkRelatedPage = IPagePopulatedToShowRevision & PageDocument;
  49. superjson.registerCustom<IShareLinkRelatedPage, string>(
  50. {
  51. isApplicable: (v): v is IShareLinkRelatedPage => {
  52. return v != null
  53. && v.toObject != null
  54. && v.lastUpdateUser != null
  55. && v.creator != null
  56. && v.revision != null;
  57. },
  58. serialize: (v) => { return superjson.stringify(v.toObject()) },
  59. deserialize: (v) => { return superjson.parse(v) },
  60. },
  61. 'IShareLinkRelatedPageTransformer',
  62. );
  63. // GrowiContextualSubNavigation for shared page
  64. // get page info from props not to send request 'GET /page' from client
  65. type GrowiContextualSubNavigationForSharedPageProps = {
  66. currentPage?: IPagePopulatedToShowRevision,
  67. isLinkSharingDisabled: boolean,
  68. }
  69. const GrowiContextualSubNavigationForSharedPage = (props: GrowiContextualSubNavigationForSharedPageProps): JSX.Element => {
  70. const { currentPage, isLinkSharingDisabled } = props;
  71. if (currentPage == null) { return <></> }
  72. return (
  73. <div data-testid="grw-contextual-sub-nav">
  74. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  75. </div>
  76. );
  77. };
  78. const SharedPage: NextPageWithLayout<Props> = (props: Props) => {
  79. useCurrentPathname(props.shareLink?.relatedPage.path);
  80. useIsSearchPage(false);
  81. useShareLinkId(props.shareLink?._id);
  82. useCurrentPageId(props.shareLink?.relatedPage._id);
  83. useCurrentUser(props.currentUser);
  84. useRendererConfig(props.rendererConfig);
  85. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  86. useIsSearchServiceReachable(props.isSearchServiceReachable);
  87. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  88. useDrawioUri(props.drawioUri);
  89. useIsContainerFluid(props.isContainerFluid);
  90. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName();
  91. const isNotFound = props.shareLink == null || props.shareLink.relatedPage == null || props.shareLink.relatedPage.isEmpty;
  92. const isShowSharedPage = !props.disableLinkSharing && !isNotFound && !props.isExpired;
  93. const shareLink = props.shareLink;
  94. const pagePath = props.shareLinkRelatedPage?.path ?? '';
  95. const revisionBody = props.shareLinkRelatedPage?.revision.body;
  96. const title = generateCustomTitleForPage(props, pagePath);
  97. const rendererOptions = generateSSRViewOptions(props.rendererConfig, pagePath);
  98. const ssrBody = <RevisionRenderer rendererOptions={rendererOptions} markdown={revisionBody ?? ''} />;
  99. const sideContents = shareLink != null
  100. ? <PageSideContents page={shareLink.relatedPage} />
  101. : <></>;
  102. // const footerContents = shareLink != null && isPopulated(shareLink.relatedPage.revision)
  103. // ? (
  104. // <>
  105. // <Comments pageId={shareLink._id} pagePath={shareLink.relatedPage.path} revision={shareLink.relatedPage.revision} />
  106. // </>
  107. // )
  108. // : <></>;
  109. const contents = (() => {
  110. const ShareLinkPageContents = dynamic(() => import('~/components/ShareLink/ShareLinkPageContents').then(mod => mod.ShareLinkPageContents), {
  111. ssr: false,
  112. loading: () => ssrBody,
  113. });
  114. return <ShareLinkPageContents page={props.shareLinkRelatedPage} />;
  115. })();
  116. return (
  117. <>
  118. <Head>
  119. <title>{title}</title>
  120. </Head>
  121. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  122. <header className="py-0 position-relative">
  123. {isShowSharedPage
  124. && <GrowiContextualSubNavigationForSharedPage currentPage={props.shareLinkRelatedPage} isLinkSharingDisabled={props.disableLinkSharing} />}
  125. </header>
  126. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  127. <MainPane
  128. sideContents={sideContents}
  129. // footerContents={footerContents}
  130. >
  131. { props.disableLinkSharing && (
  132. <div className="mt-4">
  133. <ForbiddenPage isLinkSharingDisabled={props.disableLinkSharing} />
  134. </div>
  135. )}
  136. { (isNotFound && !props.disableLinkSharing) && (
  137. <div className="container-lg">
  138. <h2 className="text-muted mt-4">
  139. <i className="icon-ban" aria-hidden="true" />
  140. <span> Page is not found</span>
  141. </h2>
  142. </div>
  143. )}
  144. { (props.isExpired && !props.disableLinkSharing && shareLink != null) && (
  145. <div className="container-lg">
  146. <ShareLinkAlert expiredAt={shareLink.expiredAt} createdAt={shareLink.createdAt} />
  147. <h2 className="text-muted mt-4">
  148. <i className="icon-ban" aria-hidden="true" />
  149. <span> Page is expired</span>
  150. </h2>
  151. </div>
  152. )}
  153. {(isShowSharedPage && shareLink != null) && (
  154. <>
  155. <ShareLinkAlert expiredAt={shareLink.expiredAt} createdAt={shareLink.createdAt} />
  156. <div className="mb-5">
  157. { contents }
  158. </div>
  159. </>
  160. )}
  161. </MainPane>
  162. </div>
  163. </>
  164. );
  165. };
  166. SharedPage.getLayout = function getLayout(page) {
  167. return (
  168. <>
  169. <DrawioViewerScript />
  170. <ShareLinkLayout>{page}</ShareLinkLayout>
  171. </>
  172. );
  173. };
  174. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  175. const req: CrowiRequest = context.req as CrowiRequest;
  176. const { crowi } = req;
  177. const { configManager, searchService, xssService } = crowi;
  178. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  179. props.isSearchServiceConfigured = searchService.isConfigured;
  180. props.isSearchServiceReachable = searchService.isReachable;
  181. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  182. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  183. props.rendererConfig = {
  184. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  185. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  186. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  187. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  188. plantumlUri: process.env.PLANTUML_URI ?? null,
  189. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  190. // XSS Options
  191. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  192. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  193. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  194. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  195. highlightJsStyleBorder: configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  196. };
  197. }
  198. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  199. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  200. props._nextI18Next = nextI18NextConfig._nextI18Next;
  201. }
  202. function getAction(props: Props): SupportedActionType {
  203. let action: SupportedActionType;
  204. if (props.isExpired) {
  205. action = SupportedAction.ACTION_SHARE_LINK_EXPIRED_PAGE_VIEW;
  206. }
  207. else if (props.shareLink == null) {
  208. action = SupportedAction.ACTION_SHARE_LINK_NOT_FOUND;
  209. }
  210. else {
  211. action = SupportedAction.ACTION_SHARE_LINK_PAGE_VIEW;
  212. }
  213. return action;
  214. }
  215. async function addActivity(context: GetServerSidePropsContext, action: SupportedActionType): Promise<void> {
  216. const req: CrowiRequest = context.req as CrowiRequest;
  217. const parameters = {
  218. ip: req.ip,
  219. endpoint: req.originalUrl,
  220. action,
  221. user: req.user?._id,
  222. snapshot: {
  223. username: req.user?.username,
  224. },
  225. };
  226. await req.crowi.activityService.createActivity(parameters);
  227. }
  228. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  229. const req = context.req as CrowiRequest<IUserHasId & any>;
  230. const { crowi, params } = req;
  231. const result = await getServerSideCommonProps(context);
  232. if (!('props' in result)) {
  233. throw new Error('invalid getSSP result');
  234. }
  235. const props: Props = result.props as Props;
  236. try {
  237. const ShareLinkModel = crowi.model('ShareLink');
  238. const shareLink = await ShareLinkModel.findOne({ _id: params.linkId }).populate('relatedPage');
  239. if (shareLink != null) {
  240. props.shareLinkRelatedPage = await shareLink.relatedPage.populateDataToShowRevision();
  241. props.isExpired = shareLink.isExpired();
  242. props.shareLink = shareLink.toObject();
  243. }
  244. }
  245. catch (err) {
  246. logger.error(err);
  247. }
  248. injectServerConfigurations(context, props);
  249. await injectNextI18NextConfigurations(context, props);
  250. await addActivity(context, getAction(props));
  251. return {
  252. props,
  253. };
  254. };
  255. export default SharedPage;